package com.example.controller;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.docx4j.Docx4J;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFont;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Author wangJinLong
 * Date 2025/10/30 19:01
 **/
@Service
public class DocxService {

    /**
     * word模板转pdf
     * @param wordFilePath
     * @param pdfFilePath
     */
    public void exportPdf(String wordFilePath, String pdfFilePath) {
        // 1. 准备替换数据
        Map<String, String> dataMap = prepareData();

        try {
            // 2. 加载Word模板
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File(wordFilePath));
            MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();

            // 3. 替换占位符 ${参数名}
            mainDocumentPart.variableReplace(dataMap);

            // 4. 设置字体映射（解决中文显示问题）
//            wordMLPackage.setFontMapper(this.getFontMapper());

            FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath);
            Docx4J.toPDF(wordMLPackage, fileOutputStream);
        } catch (Exception e) {
            throw new RuntimeException("生成PDF失败", e);
        }
    }

    /**
     * 准备模板替换数据
     */
    private Map<String, String> prepareData() {
        Map<String, String> map = new HashMap<>();
        map.put("quotaResNo", "QR-2024-0056");
        map.put("applicantNameCH", "陈明亮");
        map.put("applicantNameEN", "Chen Mingliang");
        map.put("appRef", "APP-2024-1001");
        return map;
    }

    public void convert2(String docxPath, String pdfPath) throws Exception {
        // 加载Word文档
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File(docxPath));
        Docx4J.toPDF(wordMLPackage, new FileOutputStream(pdfPath));
    }

    public void convert3(String docxPath, String pdfPath) throws Exception {
        // 加载Word文档
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File(docxPath));

        Docx4J.toPDF(wordMLPackage, new FileOutputStream(pdfPath));
    }

    private Mapper getFontMapper() {
        IdentityPlusMapper fontMapper = new IdentityPlusMapper();
        // 1. 定义完整的字体映射表：覆盖西文字体+中文字体+粗体场景
        // key：docx模板中使用的字体名（含变体）；value：系统中存在的物理字体名
        Map<String, String> fontMappings = new HashMap<>();

        // -------------------------- 关键：处理TimesNewRoman全家族 --------------------------
        fontMappings.put("TimesNewRomanPSMT", "SimSun");          // 常规体
        fontMappings.put("TimesNewRomanPS-BoldMT", "SimHei");     // 粗体→用黑体（SimHei是天然粗体，解决700字重问题）
        fontMappings.put("TimesNewRomanPS-ItalicMT", "SimSun");   // 斜体
        fontMappings.put("TimesNewRomanPS-BoldItalicMT", "SimHei");// 粗斜体→用黑体
        fontMappings.put("Times New Roman", "SimSun");            // 兼容模板中可能的“空格”写法

        // -------------------------- 处理特殊符号字体 --------------------------
        fontMappings.put("Symbol", "SimSun");                     // Symbol符号字体→用宋体替代
        fontMappings.put("ZapfDingbats", "SimSun");               // 特殊符号字体→用宋体替代

        // -------------------------- 原有中文字体映射（保留并补充） --------------------------
        fontMappings.put("隶书", "LiSu");
        fontMappings.put("宋体", "SimSun");
        fontMappings.put("微软雅黑", "Microsoft Yahei");
        fontMappings.put("黑体", "SimHei");
        fontMappings.put("楷体", "KaiTi");
        fontMappings.put("新宋体", "NSimSun");
        fontMappings.put("仿宋_GB2312", "FangSong_GB2312");
        fontMappings.put("宋体扩展", "simsun-extB");

        // -------------------------- 执行映射+容错处理 --------------------------
        fontMappings.forEach((docxFont, physicalFontName) -> {
            try {
                // 优先获取指定字体
                PhysicalFont physicalFont = PhysicalFonts.get(physicalFontName);
                if (physicalFont == null) {
                    //  fallback1：若指定字体不存在，用黑体（SimHei）替代（粗体兼容更好）
                    physicalFont = PhysicalFonts.get("SimHei");
                    System.err.println("警告：字体" + physicalFontName + "不存在，用SimHei替代");
                }
                // 关键：绑定字体+字重（解决700粗体问题）
                fontMapper.put(docxFont, physicalFont);
                // 额外处理字重映射：将“字体名+字重”也绑定（覆盖FOP的字重检测）
                fontMapper.put(docxFont + ",normal,700", physicalFont); // 粗体字重700
                fontMapper.put(docxFont + ",normal,400", physicalFont); // 常规字重400
            } catch (Exception e) {
                System.err.println("字体映射失败：" + docxFont + "→" + physicalFontName + "，原因：" + e.getMessage());
            }
        });

        // -------------------------- 特殊处理：修复宋体集合字体 --------------------------
        // SimSun通常是.ttc集合文件（含SimSun和NSimSun），强制指定集合中的字体
        PhysicalFont simSunCollection = PhysicalFonts.get("SimSun");
        if (simSunCollection != null) {
            PhysicalFonts.put("SimSun,normal,700", simSunCollection); // 强制SimSun粗体映射到集合中的字体
            PhysicalFonts.put("PMingLiU", simSunCollection);
            PhysicalFonts.put("新細明體", simSunCollection);
        }

        return fontMapper;
    }


}

